#!/bin/bash --login

usage="Usages: nth [start|stop|restart|status]"

if [ ! -n "$1" ]
then
        echo "$usage";
        exit 0
fi

process="nicu2home.ini"
cmd=$1

# start
if [ $cmd = start ]
then
  if [ $(ps -ef | grep -c ${process}) -gt 1 ]
    then
      echo 'prossess nicu2home.ini is already running，do you want to restar？'
    else
      echo 'prossess nicu2home.ini is not running, begin starting'
      `uwsgi --ini /home/nicu2home/nicu2home_django/working/nicu2home.ini`
      sleep 2
      if [ $(ps -ef | grep -c ${process}) -gt 1 ]
        then
          echo "\033[32m[OK]\033[0m  nicu2home uWSGI service is started！";
        else
          echo "\033[31m[Fail]\033[0m, nicu2home uWSGI  started Fail"
        fi
    fi

# stop
elif [ $cmd = stop ];then
        echo "shutting down nicu2home uWSGI service ...... \r\n"
        pids=$(ps x | grep ${process} | grep -v grep | awk '{print $1}')
        for pid in $pids
          do
            `kill -9 $pid`
          done
        sleep 1

        `uwsgi --stop /home/nicu2home/nicu2home_logs/uwsgi/uwsgi.pid`

        if [ $(ps -ef | grep -c ${process}) -gt 1 ]
        then
          echo "\033[31m[Fail]\033[0m nicu2home uWSGI service is NOT shut down !!"

        else
          echo "\033[32m[OK]\033[0m nicu2home uWSGI service is shut down !!";
        fi

# restart
elif [ $cmd = restart ];then
      echo -e "shutting down nicu2home uWSGI service ...... \c"
      pids=$(ps x | grep ${process} | grep -v grep | awk '{print $1}')
      for pid in $pids
        do
          `kill -9 $pid`
        done
      sleep 3
      `uwsgi --ini /home/nicu2home/nicu2home_django/working/nicu2home.ini`
      sleep 3
      if [ $(ps -ef | grep -c ${process}) -gt 1 ]
        then
          echo "\033[32m[OK]\033[0m  nicu2home uWSGI service is started！";
        else
          echo "\033[31m[Fail]\033[0m, nicu2home uWSGI  started Fail"
        fi

# status
elif [ $cmd = status ];then
  if [ $(ps -ef | grep -c ${process}) -gt 1 ]
    then
      echo 'prossess nicu2home.ini is running.'
    else
      echo 'prossess nicu2home.ini is not running.'
    fi
else
        echo "$usage";
fi
